/**
 * Copyright 2012 Woergi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gcmsms;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.gcmsms.db.DeviceEntry;
import org.gcmsms.db.Datastore;

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet(name = "Home", description = "Baseservlet for this web project", urlPatterns = { "/Home" })
public class HomeServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	private static final String GET_DEV_ATTRIBUTE = "devNick";

	public static final String ATTRIBUTE_STATUS = "sendingState";
	
	public static final String REMOVE_DEV = "removeDevForUser";
	/**
	 * 
	 * @see HttpServlet#HttpServlet()
	 */
	public HomeServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
	    String user = (String) session.getAttribute(Login.LOGIN_ATTRIBUTE);
		if (user == null) {
			String url = Login.class.getAnnotation(WebServlet.class).name();
			if (url != null) {
				response.sendRedirect(url);
			}
		}
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.print("<html><body>");
	    out.print("<head>");
	    out.print("  <title>GCMSms-Home</title>");
	    out.print("<link href='home.css' rel='stylesheet' type='text/css'/>");
	    out.print("<script type='text/javascript' href='scripts/aidplib.js' />");
	    out.print("<script type='text/javascript'>" 
	    		+ "function delDev(id) {" +
	    			"var request = new ajax.Request('POST', 'UnregisterServlet');" +
	    			"request.send(id);"
	    		+ "}"
	    		+ "</script>");
	    out.print("</head>");
	    
	    //if (request.getAttribute(ATTRIBUTE_STATUS) != null)
	    //	out.print("<pre>"+request.getAttribute(ATTRIBUTE_STATUS)+"</pre>");
	    if (session.getAttribute(ATTRIBUTE_STATUS) != null) {
	    	out.print("<pre>"+session.getAttribute(ATTRIBUTE_STATUS)+"</pre>");
	    	session.removeAttribute(ATTRIBUTE_STATUS);
	    }
	    
		if (user != null) {
			String requestingDev = (String) request.getParameter(GET_DEV_ATTRIBUTE);
			String toRemoveDev = (String) request.getParameter(REMOVE_DEV);
			if (toRemoveDev != null) {
				Datastore.getInstance().removeDevForUser(user, toRemoveDev);
			}
			
			DeviceEntry reqDev = null;
			
			List<DeviceEntry> devs = Datastore.getInstance().getDevices(user);
			out.print("<div id=logout><a href='" + Login.class.getAnnotation(WebServlet.class).name() + "'>Log out</a></div>");
			out.print("<h2>Hello " + user + ", <br />");
			out.print("you have " + devs.size() + " device(s) registered!</h2>");
			out.print("<pre>Hint: You need to have a connection between the phone and the \n"
					     + "server to send the phones registration id and contact datas.</pre>");
			if (devs.size() > 0) {
				out.print("<h3>Registered Devices</h3>\n<table>");
				out.print("<tr><th>Registered User</th><th>Device Name</th><th>Device ID</th></tr>");
				for (DeviceEntry dev : devs) {
					out.print("<tr><td>" + dev.registeredUser + "</td><td><a HREF='Home?" + GET_DEV_ATTRIBUTE 
							+ "=" + dev.deviceNick + "'> " + dev.deviceNick 
							//+ "</a> (<a HREF='Home?" + REMOVE_DEV + "=" +	dev.id + "'"
							
							+ "</a> (<a HREF='javascript:void(0)' onClick=\"delDev('" + dev.id + "');\""
							
							+ ">Remove</a>)</td><td>" + dev.deviceId +"...</td></tr>");
					if (requestingDev != null && dev.deviceNick.equals(requestingDev))
						reqDev = dev;
				}
				out.print("</table>");
			}
			
			if (reqDev != null) {
				out.print("<h3>Device: <i>" + requestingDev + "</i></h3>");
				String msgForm = "<form name='form' action='SendMessage' method='POST' >"
						+  "<input type='hidden' name='reqDev' value='" + reqDev.deviceId +"'>"
						+ "<table>"
						+ "<tr><th>Number</th><th>Message:</th></tr>"
						+ "<tr><td>"
						+ "<select name='contactName' size='10'>";
						
				boolean first = true;
				for (String cont : Datastore.getInstance().getContacts(reqDev.id)) {
					msgForm += "<option ";
					if (first)
						msgForm += "selected='selected'";
					first = false;
					msgForm += ">" + cont + "</option>";
				}
				msgForm += "</select>"
						+"</td><td><textarea name='message' cols='50' rows='10'></textarea></td></tr>"
						+ "<tr><td></td><td><input type='submit' value='Send' /></td></tr></table>";
				out.print(msgForm);
				out.print("<a HREF='Home'>Close</a>");
			}
		}
		out.print("</body></html>");
		response.setStatus(HttpServletResponse.SC_OK);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
